package com.pengy.shengxian.service;

import com.pengy.shengxian.entity.BjdDetail;
import com.pengy.shengxian.entity.BjdInfo;
import com.pengy.shengxian.mapper.BjdDetailMapper;
import com.pengy.shengxian.mapper.BjdInfoMapper;
import com.pengy.shengxian.mapper.GoodsInfoMapper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BjdInfoService {
    private static final Logger logger = LoggerFactory.getLogger(BjdInfoService.class);

    @Autowired
    private BjdInfoMapper bjdInfoMapper;
    @Autowired
    private BjdDetailMapper bjdDetailMapper;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    /**
     * 导入报价单Excel文件
     */
    @Transactional(rollbackFor = Exception.class)
    public void importBjdExcel(File file) throws Exception {
        logger.info("开始导入报价单文件: {}", file.getName());
        List<List<String>> excelData = readExcel(file);
        if (excelData == null || excelData.size() < 6) {
            throw new RuntimeException("报价单Excel数据不足，无法导入");
        }
        // 1. 组装主表数据
        BjdInfo bjdInfo = extractBjdInfoFromExcel(excelData);
        // 2. 处理报价单覆盖逻辑
        handleBjdOverwrite(bjdInfo);
        // 3. 插入新的主表数据
        bjdInfoMapper.insert(bjdInfo);
        logger.info("报价单主表插入成功: {}", bjdInfo.getBjdHjkCode());
        // 2. 组装明细数据
        List<BjdDetail> detailList = extractBjdDetailFromExcel(excelData, bjdInfo);
        if (!detailList.isEmpty()) {
            bjdDetailMapper.batchInsert(detailList);
            logger.info("报价单明细插入成功，数量: {}", detailList.size());
            // 3. 批量补全明细商品信息
            batchUpdateDetailGoodsInfo(detailList, bjdInfo.getId());
        }
    }

    /**
     * 导入报价单Excel文件，返回明细条数
     */
    @Transactional(rollbackFor = Exception.class)
    public int importBjdExcelWithDetailCount(File file) throws Exception {
        logger.info("开始导入报价单文件: {}", file.getName());
        List<List<String>> excelData = readExcel(file);
        if (excelData == null || excelData.size() < 6) {
            throw new RuntimeException("报价单Excel数据不足，无法导入");
        }
        BjdInfo bjdInfo = extractBjdInfoFromExcel(excelData);
        // 处理报价单覆盖逻辑
        handleBjdOverwrite(bjdInfo);
        // 插入新的主表数据
        bjdInfoMapper.insert(bjdInfo);
        logger.info("报价单主表插入成功: {}", bjdInfo.getBjdHjkCode());
        List<BjdDetail> detailList = extractBjdDetailFromExcel(excelData, bjdInfo);
        int detailCount = detailList.size();
        if (!detailList.isEmpty()) {
            bjdDetailMapper.batchInsert(detailList);
            logger.info("报价单明细插入成功，数量: {}", detailList.size());
            batchUpdateDetailGoodsInfo(detailList, bjdInfo.getId());
        }
        return detailCount;
    }

    /**
     * 读取Excel文件内容
     */
    private List<List<String>> readExcel(File file) throws Exception {
        List<List<String>> data = new ArrayList<>();
        try (FileInputStream fis = new FileInputStream(file); Workbook workbook = WorkbookFactory.create(fis)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    cell.setCellType(CellType.STRING);
                    rowData.add(cell.getStringCellValue().trim());
                }
                data.add(rowData);
            }
        }
        return data;
    }

    /**
     * 从Excel数据提取主表信息
     */
    private BjdInfo extractBjdInfoFromExcel(List<List<String>> excelData) throws Exception {
        BjdInfo info = new BjdInfo();
        info.setBjdDept("T001"); // 固定赋值T001
        info.setBjdHjkCode(getCell(excelData, 0, 1));
        info.setBjdInfoDate(parseDate(getCell(excelData, 1, 1)));
        info.setBjdInfoStartDate(parseDate(getCell(excelData, 2, 1)));
        info.setBjdInfoEndDate(parseDate(getCell(excelData, 3, 1)));
        info.setBjdInfoSupplier("AHYJSX");
        info.setBjdInfoStatus(1);
        info.setBjdInfoSyncStatus(0);
        info.setBjdInfoWriDate(new Date());
        // 其他字段不处理
        return info;
    }

    /**
     * 从Excel数据提取明细信息
     */
    private List<BjdDetail> extractBjdDetailFromExcel(List<List<String>> excelData, BjdInfo bjdInfo) {
        List<BjdDetail> list = new ArrayList<>();
        Integer outbjdInfoId = bjdInfo.getId() == null ? null : bjdInfo.getId().intValue();
        // 明细从第6行开始
        for (int i = 5; i < excelData.size(); i++) {
            List<String> row = excelData.get(i);
            if (row.size() < 2) continue;
            BjdDetail detail = new BjdDetail();
            detail.setBjdInfoCode(bjdInfo.getBjdHjkCode());
            detail.setOutbjdInfoId(outbjdInfoId);
            detail.setBjdDetailGoodsName(row.get(0));
            detail.setBjdDetailGoodsCode(row.get(1));
            detail.setBjdDetailGoodsSupplier("安徽叶记生鲜食品配送有限公司");
            // 其他字段后续批量补全
            list.add(detail);
        }
        return list;
    }

    /**
     * 处理报价单覆盖逻辑
     */
    private void handleBjdOverwrite(BjdInfo bjdInfo) {
        BjdInfo exist = bjdInfoMapper.selectByBjdHjkCode(bjdInfo.getBjdHjkCode());
        if (exist != null) {
            logger.info("报价单已存在，开始覆盖: {}", bjdInfo.getBjdHjkCode());
            // 删除原有明细数据
            bjdDetailMapper.deleteByBjdInfoId(exist.getId());
            logger.info("删除原有报价单明细数据成功，报价单ID: {}", exist.getId());
            // 删除原有主表数据
            bjdInfoMapper.deleteById(exist.getId());
            logger.info("删除原有报价单主表数据成功，报价单ID: {}", exist.getId());
        }
    }

    /**
     * 批量补全明细商品信息
     */
    private void batchUpdateDetailGoodsInfo(List<BjdDetail> detailList, Long bjdInfoId) {
        if (detailList == null || detailList.isEmpty()) return;
        String bjdInfoCode = detailList.get(0).getBjdInfoCode();
        try {
            bjdDetailMapper.updateDetailFieldsByBjdInfoCode(bjdInfoCode);
            logger.info("批量更新报价单明细商品信息成功，报价单号: {}", bjdInfoCode);
        } catch (Exception e) {
            logger.error("批量更新报价单明细商品信息失败，报价单号: {}", bjdInfoCode, e);
            throw new RuntimeException("更新报价单明细商品信息失败: " + e.getMessage(), e);
        }
    }

    private String getCell(List<List<String>> data, int row, int col) {
        if (row < data.size() && col < data.get(row).size()) {
            return data.get(row).get(col);
        }
        return "";
    }

    private Date parseDate(String str) throws Exception {
        if (str == null || str.isEmpty()) return null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(str);
    }
}